<template>
    <div class="container">
        <div class="add-btn">
            <el-button type="primary" @click="handleQsDialog('add')">新增问卷</el-button>
        </div>
        <div class="search-content">
            <el-form :model="searchContent" ref="searchFrom" :inline="true">
                <el-form-item prop="questionnaire_id" label="问卷ID：">
                    <el-input 
                        v-model="searchContent.questionnaire_id" placeholder="问卷ID" maxlength="32">
                    </el-input>
                </el-form-item>
                <el-form-item prop="title" label="问卷名称：">
                    <el-input 
                        v-model="searchContent.title" placeholder="问卷名称" maxlength="32">
                    </el-input>
                </el-form-item>
                <el-form-item label="有效时间：">
                    <el-date-picker
                        v-model="selectTime[0]"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间" 
                        end-placeholder="结束时间"
                        value-format="timestamp"
                        format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']"
                        @change="val => handleDateChange(val, '')">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="创建日期：">
                    <el-date-picker
                        v-model="selectTime[1]"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间" 
                        end-placeholder="结束时间"
                        value-format="timestamp"
                        format="yyyy-MM-dd HH:mm:ss"
                        :default-time="['00:00:00', '23:59:59']"
                        @change="val => handleDateChange(val, 'create')">
                    </el-date-picker>
                </el-form-item>
                <el-form-item prop="status" label="问卷状态：">
                    <el-select v-model="searchContent.status" clearable>
                        <el-option 
                            v-for="item of statusType" :value="item.value" :label="item.name" :key="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch(true)">搜索</el-button>
                    <el-button type="primary" @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="search-list">
            <el-table border :data="dataList" :height="oHeight">
                <el-table-column type="selection" width="60" align="center"></el-table-column>
                <el-table-column label="ID" prop="questionnaire_id" width="80" align="center"></el-table-column>
                <el-table-column 
                    prop="title" label="问卷名称" min-width="180" align="center" show-overflow-tooltip>
                </el-table-column>
                <el-table-column 
                    prop="create_time" label="创建时间" min-width="160" align="center">
                </el-table-column>
                <el-table-column label="有效时间" min-width="160" align="center" #default="{ row }">
                    {{ row.start_time }}<br>
                    {{ row.end_time }}
                </el-table-column>
                <el-table-column 
                    prop="status" label="问卷状态" min-width="100" align="center">
                    <template #default="{ row }">
                        <span :class="`status-${row.status}`">
                            {{ statusType[row.status] ? statusType[row.status].name : '--' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="120" align="center">
                    <template #default="{ row }">
                        <el-dropdown size="mini" trigger="click">
                            <el-button type="primary">
                                展开<i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown" class="dropdown-btn el-dropdown__button-group">
                                <el-dropdown-item>
                                    <el-button type="text" @click="handleDrawer('store', row)">
                                        使用店铺
                                    </el-button>
                                </el-dropdown-item>
                                <el-dropdown-item>
                                    <el-button type="text" @click="handleQsDialog('preview', row)">
                                        问卷预览
                                    </el-button>
                                </el-dropdown-item>
                                <template v-if="row.status >= 1">
                                    <el-dropdown-item>
                                        <el-button type="text" @click="handleDrawer('record', row)">
                                            答题记录
                                        </el-button>
                                    </el-dropdown-item>
                                    <el-dropdown-item v-if="row.status == 1">
                                        <el-button type="text" @click="handleUpdate(row)">
                                            停用问卷
                                        </el-button>
                                    </el-dropdown-item>
                                </template>
                                <template v-else>
                                    <el-dropdown-item>
                                        <el-button type="text" @click="handleQsDialog('edit', row)">
                                            编辑问卷
                                        </el-button>
                                    </el-dropdown-item>
                                    <el-dropdown-item>
                                        <el-button type="text"  @click="handleDel(row.questionnaire_id, row.title)">
                                            删除问卷
                                        </el-button>
                                    </el-dropdown-item>
                                </template>
                                <el-dropdown-item>
                                    <el-button type="text" @click="handleQsDialog('copy', row)">
                                        复制问卷
                                    </el-button>
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="bottom flex-item">
            <div class="btn-group">
                <el-button type="primary" @click="handleExport">导出</el-button>
            </div>
            <div class="paginationOne">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="pageArr.page"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageArr.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="pageArr.total">
                </el-pagination>
            </div>
        </div>
        <qs-dialog 
            :visible.sync="dialogOptions.visible" :data="dialogOptions.data" @update="getData" :action="dialogOptions.action">
        </qs-dialog>
        <preview-dialog :visible.sync="dialogOptions.previewVisible" :data="dialogOptions.previewData"></preview-dialog>
        <record-drawer :visible.sync="drawerOptions.visible" :data="drawerOptions.data"></record-drawer>
        <store-drawer :visible.sync="drawerOptions.storeVisible" :data="drawerOptions.storeData"></store-drawer>
    </div>
</template>
<script>
import { resize } from "@/common/js/height.js"
import { objScreen } from "@/common/js/util.js"
import qsDialog from './qs-dialog.vue'
import previewDialog from './preview-dialog.vue'
import recordDrawer from './record-drawer.vue'
import storeDrawer from './store-drawer.vue'
import { statusType, actionType } from './action_types.js'
export default {
    components: { qsDialog, previewDialog, recordDrawer, storeDrawer },
    data() {
        return {
            searchContent: {
                questionnaire_id: '',     // 问卷ID
                title: '',                // 问卷名称
                start_time: '',           // 有效时间[开始]
                end_time: '',             // 有效时间[结束]
                create_time_start: '',    // 创建日期[开始]
                create_time_end: '',      // 创建日期[结束]
                status: '',               // 问卷状态
                is_search: false          // 是否处于搜索
            },
            selectTime: [],               // 时间 [[start, end]]
            pageArr: {    
                page: 1,                  // 当前页码
                pageSize: +localStorage.getItem('pageSize') || 20, // 每页显示数量
                total: 0                  // 数据总数
            },
            dataList: [],                 // 列表数据
            dialogOptions: {              // 基础参数
                visible: false,           // 问卷编辑/添加
                data: {},
                previewVisible: false,    // 问卷预览
                previewData: {},
                action: ''
            },
            drawerOptions: {              // 基础参数
                visible: false,           // 问卷详情
                data: {},
                storeVisible: false,      // 使用店铺
                storeData: {}
            },
            statusType: statusType(true), // 问卷状态
            actionTypeJson: actionType(true), // 问卷类型
            detail: {},
            oHeight: 600,
        }
    },
    methods: {
        handleDateChange(val = null, key = '') {
            let startTime = 'start_time', endTime = 'end_time'
            if (key) {
                startTime = 'create_time_start'
                endTime = 'create_time_end'
            }
            if (val) {
                this.searchContent[startTime] = val[0] / 1000
                this.searchContent[endTime] = val[1] / 1000
            } else {
                this.searchContent[startTime] = null
                this.searchContent[endTime] = null
            }
        },
        async getData() {
            try {
                const { pageSize, page } = this.pageArr
                let datas = { pageSize, page }
                if (this.searchContent.is_search) {
                    datas = { ...datas, ...this.searchContent }
                }
                objScreen(datas)
                const res = await this.$http.get('/admin/yt_car/index.php?act=questionnaire&op=questionnaireList', { params: datas })
                if (res.code == 1) {
                    this.dataList = res.data?.list || []
                    this.pageArr.total = +res.data.totalCount
                }
            } catch (error) {
                error && this.$message.error(`${error}`)
            }
        },
        handleSizeChange(pageSize) {
            localStorage.setItem('pageSize', pageSize)
            this.pageArr.pageSize = pageSize
            this.pageArr.page = 1
            this.getData()
        },
        handleCurrentChange(page) {
            this.pageArr.page = page
            this.getData()
        },
        handleSearch(is_search = true) {
            this.searchContent.is_search = is_search
            this.pageArr.page = 1
            this.getData()
        },
        handleReset() {
            this.selectTime = []
            this.$refs.searchFrom.resetFields()
            this.handleDateChange()
            this.handleDateChange(null, 'create')
            if (!this.searchContent.is_search) return
            this.handleSearch(false)
        },
        handleQsDialog(action = "add", row = {}) {
            if (action === "preview") {
                this.dialogOptions.previewVisible = true
                this.dialogOptions.previewData = row
            } else {
                this.dialogOptions.visible = true
                this.dialogOptions.data = row
                this.dialogOptions.action = action
            }
        },
        handleDrawer(type = 'record', row) {
            const { questionnaire_id, title, status } = row
            if (type == 'record') {
                this.drawerOptions.visible = true
                this.drawerOptions.data = { questionnaire_id, title }
            } else {
                this.drawerOptions.storeVisible = true
                this.drawerOptions.storeData = { questionnaire_id, status }
            }
        },
        async handleUpdate(row) {
            try {
                const { questionnaire_id, status } = row
                let content = status == 1 ? '停用' : '开启'
                await this.$alert(`确定${content}？`, "温馨提示", {
                    type: 'warning',
                    showCancelButton: true
                })
                const res = await this.$http.get(
                    "/admin/yt_car/index.php?act=questionnaire&op=stopQuestionnaire", { params: {questionnaire_id} }
                )
                if (res.code == 1) {
                    this.$message.success(content + "成功")
                    row.status = +!!status
                    this.getData()
                } else {
                    throw res.msg
                }
            } catch (error) {
                error && error != 'cancel' && this.$message.error(`${error}`)
            }
        },
        async handleDel(questionnaire_id, title) {
            try {
                await this.$alert(`确定删除：${title}？`, "温馨提示", {
                    type: 'warning',
                    showCancelButton: true
                })
                const res = await this.$http.get(
                    "/admin/yt_car/index.php?act=questionnaire&op=delQuestionnaire", { params: { questionnaire_id } }
                )
                if (res.code == 1) {
                    this.$message.success("删除成功")
                    this.getData()
                } else {
                    throw res.msg
                }
            } catch (error) {
                error && error != 'cancel' && this.$message.error(`${error}`)
            }
        },
        handleExport() {
            const origin = this.$store.state.location.origin
            const datas = { ...this.searchContent }
            const params = []
            Object.entries(datas).forEach(item => {
                if (item[1] || item[1] === 0) {
                    params.push(`${item[0]}=${item[1]}`)
                }
            })
            const href = origin + "/admin/yt_car/index.php?act=questionnaire&op=questionnaireList&is_export=1&"+ params.join("&")
            window.location.href = href
        },
    },
    created() {
        this.getData()
    },
    mounted() {
        resize(this)
    }
}
</script>
<style lang="scss" scoped>
.add-btn {
    position: absolute;
    top: 10px;
    right: 12px;
}
.bottom {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.status-0 { color: #999999 }
.status-1 { color: #67C23A }
.status-2 { color: #333333 }
.status-3 { color: #F56C6C }
</style>